package service

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/robfig/cron"
	"hoop_srv/basic/config"
	__ "hoop_srv/basic/proto"
	"hoop_srv/handler/models"
	"hoop_srv/pkg"
	"log"
	"time"
)

type Server struct {
	__.UnimplementedHoopServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	kay, val := "lock", fmt.Sprintf("%d", time.Now().UnixNano())

	var course models.Course
	err := course.GetCourse(int(in.TeacherId))
	if err != nil {
		return nil, fmt.Errorf("获取课程信息失败")
	}
	if course.Id == 0 {
		return nil, fmt.Errorf("该课程不存在")
	}
	startTime, _ := time.Parse(time.DateTime, in.StartTime)
	endTime, _ := time.Parse(time.DateTime, in.EndTime)

	order := models.Order{
		OrderSn:   uuid.NewString(),
		Title:     in.Title,
		TeacherId: uint(in.TeacherId),
		StartTime: startTime,
		EndTime:   endTime,
	}
	result, err := config.Rdb.SetNX(config.Ctx, kay, val, time.Minute*15).Result()

	if err != nil || result == false {
		return nil, fmt.Errorf("上锁失败")
	}

	err = order.CreateOrder()
	if err != nil {
		return nil, fmt.Errorf("创建订单失败")
	}
	fmt.Println(pkg.Alipay(order.OrderSn, fmt.Sprintf("%.2f", course.Price)))

	Scheduledtasks()

	order.OrderStatus = 2
	err = order.UpdateStatus()
	if err != nil {
		return nil, fmt.Errorf("修改订单状态失败")
	}
	config.Rdb.Del(config.Ctx, kay)
	return &__.CreateOrderResp{
		OrderId: int64(order.Id),
	}, nil
}

// 添加课程
func (s *Server) CreateCourse(_ context.Context, in *__.CreateCourseReq) (*__.CreateCourseResp, error) {
	course := models.Course{
		Title:      in.Title,
		TeacherUrl: in.TeacherUrl,
		Price:      float64(in.Price),
	}
	err := course.CreateCouse()
	if err != nil {
		return nil, fmt.Errorf("创建课程失败")
	}
	return &__.CreateCourseResp{
		Course: int64(course.Id),
	}, nil
}
func Scheduledtasks() {
	c := cron.New()
	spec := "* */15 * * * ?"
	err := c.AddFunc(spec, func() {
		var order models.Order
		if order.OrderStatus == 1 {
			fmt.Errorf("该订单未支付")
			return
		}
		log.Println("cron running:", order.Id)
	})
	fmt.Println(err)
	c.Start()

	select {}
}
